import React, { Component } from 'react'
import './index.css'
import Header from './components/Header'
import Main from './components/Main'
import Footer from './components/Footer'

class App extends Component {
  state = {
    // 数据
    list: [
      { id: '1', title: '吃饭', done: true },
      { id: '2', title: '睡觉', done: true },
      { id: '3', title: '打代码', done: false },
      { id: '4', title: '吃喝玩乐', done: false },
    ],
    //  是否全选
    active: 'All',

    editId: -1,
  }

  // 增加
  addTodo = (title) => {
    const { list } = this.state
    this.setState({
      list: [
        ...list,
        { id: new Date().toLocaleString(), title: title, done: false },
      ],
    })
  }

  // 删除
  remove = (id) => {
    const { list } = this.state
    this.setState({
      ...list,
      list: list.filter((item) => item.id !== id),
    })
  }

  // 单选
  checked = (id) => {
    const { list } = this.state
    this.setState({
      list: list.map((item) => {
        if (item.id === id) {
          return { ...item, done: !item.done }
        }
        return item
      }),
    })
  }

  // 全选
  checkedAll = (e) => {
    // console.log('全选')
    const flag = e.target.checked
    this.setState({
      list: this.state.list.map((item) => {
        if (flag === true) {
          return { ...item, done: true }
        } else {
          return { ...item, done: false }
        }
      }),
    })
  }

  // 显示列表
  list = () => {
    const { active, list } = this.state
    if (active === 'All') {
      return list
    } else if (active === 'Active') {
      return list.filter((item) => !item.done)
    } else {
      return list.filter((item) => item.done)
    }
  }

  // 切换显示列表
  changeList = (active) => {
    this.setState({
      active,
    })
  }

  // 清除已完成
  clearDone = () => {
    console.log('清除已完成')
    this.setState({
      list: this.state.list.filter((item) => !item.done),
    })
  }

  // 双击显示输入框   TODO:   待完善
  showEdit = (id) => {
    console.log('showEdit',id)
    this.editId = id;
  }

  render() {
    return (
      <section className="todoapp">
        <Header addTodo={this.addTodo} />
        <Main
          list={this.list()}
          remove={this.remove}
          checked={this.checked}
          checkedAll={this.checkedAll}
          showEdit={this.showEdit}
        />
        <Footer
          changeList={this.changeList}
          list={this.list()}
          clearDone={this.clearDone}
        />
      </section>
    )
  }
}

export default App
